import { mapMutations } from 'vuex';
import { userInfo, userUploadAvatar, userUpdateInfo } from '@/api/user.js';

export default {
	data() {
		return {
			imageStyles: {
				width: 64,
				height: 64,
				border: {
					radius: '50%'
				}
			},
			// 基础表单数据
			info: {
				avatar: '/static/user/default-avatar.png',
				userName: '',
				sex: 0,
				phone: '',
				email: '',
				birthday: 1627529992399,
				city: '',
				sign: '',
			},
			fileLists: [{
				url: '/static/user/default-avatar.png',
				extname: 'png',
				name: 'default-avatar.png'
			}],
			// 单选数据源
			sexs: [{
				text: '未知',
				value: 0
			},{
				text: '男',
				value: 1
			}, {
				text: '女',
				value: 2
			}],
			// 校验规则
			rules: {
				userName: {
					rules: [{
						required: true,
						errorMessage: '用户名不能为空'
					}]
				},
				phone: {
					rules: [{
						required: true,
						errorMessage: '请填写手机号码',
					}, {
						validateFunction: function(rule, value, data, callback) {
							let iphoneReg = (
								/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
							); //手机号码
							if (!iphoneReg.test(value)) {
								callback('手机号码格式不正确，请重新填写')
							}
						}
					}]
				}
			},
		};
	},
	watch: {
		'info.avatar': {
			handler: function(val){
				const url = val;
				const name = url.substring(url.lastIndexOf('/')+1);
				const extname = name.substring(name.lastIndexOf('.')+1);
				const fileData = [{
					url: url,
					extname: extname,
					name: name
				}];
				this.fileLists = fileData;
			},
		}
	},
	created() {
		this.loadData();
	},
	methods: {
		...mapMutations(['updateUserInfo']),
		loadData() {
			userInfo().then(response => {
				this.info = response.data;
			});
		},
		//图片上传
		select(e){
			const tempFilePaths = e.tempFilePaths;
			//获取图片临时路径
			const imgUrl = tempFilePaths[0];
			//上传头像
			userUploadAvatar(imgUrl).then(res => {
				const resData = JSON.parse(res);
				this.info.avatar=resData.data;
			});
		},
		//提交
		submit(ref) {
			this.$refs[ref].validate().then(res => {
				//console.log('校验成功', res);
				userUpdateInfo(this.info).then(response => {
					uni.showToast({
						title: `修改成功`
					});
					
				   //更新本地缓存
				    let userInfo = uni.getStorageSync('user') || '';
					if(userInfo.id){
						userInfo.avatar = this.info.avatar;
						userInfo.userName = this.info.userName;
						userInfo.sign = this.info.sign;
						uni.setStorageSync('user',userInfo);
						
						//状态管理
						this.updateUserInfo(userInfo);
					}
					
					uni.navigateBack();
				});
			}).catch(err => {
				console.log('err', err);
			})
		},
	},
}